<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 栏目模型
// +----------------------------------------------------------------------
namespace app\admin\model\cms;

use app\admin\model\cms\CategoryPriv;
use think\Db;
use think\facade\Cache;
use think\Model;

/**
 * 模型
 */
class Category extends Model
{
    protected static $arrparent;
    protected static $arrchild;

    protected $auto = ['setting'];

    public function setSettingAttr($value)
    {
        return is_array($value) ? serialize($value) : $value;
    }

    public static function init()
    {
        $cmsConfig = get_addon_config("cms");
        self::afterWrite(function ($row) use ($cmsConfig) {
            if (isset($cmsConfig['web_site_weburlpush']) && $cmsConfig['web_site_weburlpush']) {
                hook("weburlpush", buildCatUrl($row->id, '', true, true));
            }
            if (isset($row['priv_groupid'])) {
                CategoryPriv::update_priv($row->id, $row->priv_groupid, 0);
            }
        });
        self::afterInsert(function ($row) {
            cache('Category', null);
            if ($row['type'] == 1) {
                //增加默认单页
                (new Page)->savePage([
                    'catid' => $row->id,
                    'title' => $row->catname,
                ]);
            }
        });
        self::beforeUpdate(function ($row) {
            //应用模板到所有子栏目
            if (isset($row['template_child']) && $row['template_child']) {
                $idstr                        = self::get_arrchildid($row->id);
                $data                         = $setting                         = unserialize($row->setting);
                $setting['category_template'] = $data['category_template'] ?? '';
                $setting['list_template']     = $data['list_template'] ?? '';
                $setting['show_template']     = $data['show_template'] ?? '';
                $setting['page_template']     = $data['page_template'] ?? '';
                Db::name('category')->where('id', 'in', $idstr)->update(['setting' => serialize($setting)]);
            }
        });
        self::afterUpdate(function ($row) {
            $changedData = $row->getChangedData();
            //其他类型改为单页也要新增单页
            if ($row['type'] == 1 && isset($changedData['type'])) {
                //增加默认单页
                (new Page)->savePage([
                    'catid' => $row->id,
                    'title' => $row->catname,
                ]);
            }
            //更新栏目缓存
            cache('Category', null);
            getCategory($row->id, '', true);
        });
        self::beforeDelete(function ($row) {
            //是否存在子栏目
            if (self::where('parentid', $row->id)->find()) {
                throw new \Exception("栏目含有子栏目，不得删除！");
            }
            $catInfo = self::get($row->id);
            //检查是否存在数据，存在数据不执行删除
            if ($catInfo['modelid'] && $catInfo['type'] == 2) {
                $tbname = ucwords(getModel($catInfo['modelid'], 'tablename'));
                if ($tbname && Db::name($tbname)->where(['catid' => $row->id])->find()) {
                    throw new \Exception("栏目含有信息，不得删除！");
                }
            } elseif ($catInfo['type'] == 1) {
                Db::name('page')->where(['catid' => $row->id])->delete();
            }
        });
    }

    /**
     *
     * 获取父栏目ID列表
     * @param integer $catid              栏目ID
     * @param array $arrparentid          父目录ID
     * @param integer $n                  查找的层次
     */
    public static function get_arrparentid($catid, $arrparentid = '', $n = 1)
    {
        if (empty(self::$arrparent)) {
            self::$arrparent = cache('Category');
        }
        if ($n > 10 || !is_array(self::$arrparent) || !isset(self::$arrparent[$catid])) {
            return false;
        }
        //获取当前栏目的上级栏目ID
        $parentid = self::$arrparent[$catid]['parentid'];
        //所有父ID
        $arrparentid = $arrparentid ? $parentid . ',' . $arrparentid : $parentid;
        if ($parentid) {
            $arrparentid = self::get_arrparentid($parentid, $arrparentid, ++$n);
        } else {
            self::$arrparent[$catid]['arrparentid'] = $arrparentid;
        }
        return (string) $arrparentid;
    }

    /**
     *
     * 获取子栏目ID列表
     * @param $catid 栏目ID
     */
    public static function get_arrchildid($catid)
    {
        if (!self::$arrchild) {
            self::$arrchild = cache('Category');
        }
        $arrchildid = $catid;
        if (is_array(self::$arrchild)) {
            foreach (self::$arrchild as $id => $cat) {
                if ($cat['parentid'] && $id != $catid && $cat['parentid'] == $catid) {
                    $arrchildid .= ',' . self::get_arrchildid($id);
                }
            }
        }
        return (string) $arrchildid;
    }

}
